package com.letianpai.activity.chat;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransfer.Status;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferNegotiator;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.letianpai.R;
import com.letianpai.activity.ShowImageActivity;
import com.letianpai.activity.family.FamilyListActivity;
import com.letianpai.adapter.chat.ChatInformationAdapter;
import com.letianpai.bean.FriendInfo;
import com.letianpai.bean.Msg;
import com.letianpai.common.tool.ImageTool;
import com.letianpai.db.ChatInformation;
import com.letianpai.db.DBUtiles;
import com.letianpai.utils.ChatUtils;
import com.letianpai.utils.TimeRender;
import com.letianpai.utils.Utils;
import com.letianpai.utils.XmppTool;
import com.letianpai.view.RecordButton;
import com.letianpai.view.RecordButton.OnFinishedRecordListener;

public class ChatActivity extends Activity {
	Bitmap mb = null, ub;// 聊天双方头像
	EditText writeContent;
	Button write, addAction, send1, writeBack;
	View frameLayout, headBackText;
	TextView headText, headShare;
	private List<Msg> listMsg = new LinkedList<Msg>();// 显示消息
	String path = "";
	String userChat = "", userName;
	static String chatName;
	public String chatUserId;
	String sendFilePath = "";
	Bitmap bp = null;// 发送图片
	Uri uri;

	
	
	
	private String userChatSendFile = "";// 给谁发文件
	Msg ms = new Msg();
	public static ChatInformationAdapter adapter;
	public static ArrayList<Msg> list;
	Chat newchat;
	public static ListView listview;
	View chat_picture, photograph, gallery;
	boolean chatFlag = false;
	// 发送文件
	private OutgoingFileTransfer sendTransfer;
	public static String FILE_ROOT_PATH = Environment
			.getExternalStorageDirectory().getPath() + "/chat/file";
	public static String RECORD_ROOT_PATH = Environment
			.getExternalStorageDirectory().getPath() + "/chat/record/";
	RecordButton mRecordButton;// 自定义发语音控件
	SharedPreferences sp;
	ArrayList<String> listChat;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.e_family_chat);
		AudioManager audioManager = (AudioManager) this
				.getSystemService(this.AUDIO_SERVICE);
		audioManager.setSpeakerphoneOn(true);

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("cn.abel.action.broadcast");
		this.registerReceiver(new MyBroadcastReciver(), intentFilter);

		initView();// 初始化
		chatFamily();
		sendSound();
		receivedFile();
	}

	public class MyBroadcastReciver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("cn.abel.action.broadcast")) {
				String from = intent.getStringExtra("from");
				if ((userChat + "/Smack").equals(from)) {
					Msg msg = (Msg) intent.getSerializableExtra("msg");
					list.add(msg);
					adapter.setArraylist(list);
					adapter.notifyDataSetChanged();
					ChatActivity.listview.setSelection(ChatActivity.adapter
							.getCount() - 1);
				}
			}
		}

	}

	public void initView() {
		chatName = getIntent().getStringExtra("name");// 聊天对象
		Log.d("zzzz", chatName + "聊天对象");

		// 设置聊天对象昵称
		headText = (TextView) findViewById(R.id.headText);
		headText.setText(getIntent().getStringExtra("nick"));
		// 清空未读消息
		for (FriendInfo info : FamilyListActivity.arrayList) {

			if ((info.getUsername() + "@AY14050414574271995aZ")
					.equals(chatName)) {
				info.setMessageCount(0);
			}
		}
		FamilyListActivity.fd.setArrayList(FamilyListActivity.arrayList);
		FamilyListActivity.fd.notifyDataSetChanged();

		frameLayout = findViewById(R.id.frameLayout);
		sp = getSharedPreferences("myPref", MODE_WORLD_READABLE);
		userName = sp.getString("username", "");
		list = new ArrayList<Msg>();
		list.clear();
		gallery = findViewById(R.id.gallery);
		photograph = findViewById(R.id.photograph);
		gallery.setOnClickListener(new ChatClick());
		photograph.setOnClickListener(new ChatClick());
		headBackText = findViewById(R.id.headBackText);
		chatUserId = getIntent().getStringExtra("chatUserId");
		writeContent = (EditText) findViewById(R.id.writeContent);
		write = (Button) findViewById(R.id.write);
		addAction = (Button) findViewById(R.id.addAction);
		addAction.setOnClickListener(new ChatClick());
		send1 = (Button) findViewById(R.id.send1);
		writeBack = (Button) findViewById(R.id.writeBack);
		chat_picture = findViewById(R.id.chat_picture);
		adapter = new ChatInformationAdapter(this, list, mb, ub);
		listview = (ListView) findViewById(R.id.listView);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(new ChatInformationClick());
		write.setOnClickListener(new ChatClick());
		send1.setOnClickListener(new ChatClick());
		writeBack.setOnClickListener(new ChatClick());
		headBackText.setOnClickListener(new ChatClick());
		headShare = (TextView) findViewById(R.id.headShare);
		headShare.setText("");
		// 获取聊天双方的头像
		// getUserBitmap();
		// 获取历史聊天记录
		listChat = DBUtiles.selectInformation(ChatActivity.this, userName,
				chatName);
		for (String a : listChat) {
			Gson gson = new Gson();
			Msg message = new Msg();
			message = gson.fromJson(a, new TypeToken<Msg>() {
			}.getType());
			message.setReceive("success");
			list.add(message);
		}

		listview.setSelection(adapter.getCount() - 1);
		adapter.setArraylist(list);
		adapter.notifyDataSetChanged();

	}

	/*
	 * 聊天-收消息
	 */
	public void chatFamily() {
		userChat = this.getIntent().getStringExtra("name");
		// 消息监听
		ChatManager cm = XmppTool.getConnection().getChatManager();
		newchat = cm.createChat(chatUserId, null);
		Log.d("zzzz", chatUserId + "聊天的人是谁啊");
		// cm.addChatListener(new mChatManagerListener());
	}

	class mChatManagerListener implements ChatManagerListener {

		@Override
		public void chatCreated(Chat chat, boolean able) {
			chat.addMessageListener(new MessageListener() {

				@Override
				public void processMessage(Chat chat2, Message message) {
					Log.d("zzzz", message.toString() + "这里是ChatActivity监听到好友消息");
					if (message.getFrom().contains(userChat)) {
						String[] args = new String[] { userChat,
								message.getBody(), TimeRender.getDate(), "IN" };
						// 在handler里取出来显示消息
						android.os.Message msg = handler.obtainMessage();
						Bundle budler = new Bundle();
						budler.putString("message", message.getBody());
						msg.setData(budler);
						msg.what = 1;
						msg.obj = args;
						msg.sendToTarget();
					} else {
					}

				}
			});
		}

	}

	/*
	 * 发语音
	 */
	public void sendSound() {
		mRecordButton = (RecordButton) findViewById(R.id.record_button);
		path = RECORD_ROOT_PATH;
		File file = new File(path);
		file.mkdirs();
		path += "/" + System.currentTimeMillis() + ".amr";
		mRecordButton.setSavePath(path);
		mRecordButton
				.setOnFinishedRecordListener(new OnFinishedRecordListener() {

					@Override
					public void onFinishedRecord(String audioPath, int time) {

						if (audioPath != null) {

							try {
								// 自己显示消息
								Msg myChatMsg = new Msg(chatUserId, time
										+ "语音消息", TimeRender.getDate(),
										Msg.FROM_TYPE[1], Msg.TYPE[0],
										Msg.STATUS[3], time + "", audioPath);
								list.add(myChatMsg);

								String[] pathStrings = audioPath.split("/"); // 文件名
								// 发送 对方的消息
								String fileName = null;
								if (pathStrings != null
										&& pathStrings.length > 0) {
									fileName = pathStrings[pathStrings.length - 1];
								}
								Msg sendChatMsg = new Msg(chatUserId, time
										+ "语音消息", TimeRender.getDate(),
										Msg.FROM_TYPE[0], Msg.TYPE[0],
										Msg.STATUS[3], time + "", fileName);

								// 刷新适配器
								adapter.notifyDataSetChanged();
								listview.setSelection(adapter.getCount() - 1);
								// 发送消息
								newchat.sendMessage(Msg.toJson(sendChatMsg));
								sendFile(audioPath);//
								Log.d("zzzz", audioPath + "发送的文件名称");
								ChatUtils.saveChat(ChatActivity.this,
										myChatMsg, chatName, userName);
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else {
							Toast.makeText(ChatActivity.this, "发送失败",
									Toast.LENGTH_SHORT).show();
						}

					}
				});
	}

	/*
	 * Handle
	 */
	public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case 1:
				// 清空未读消息

				for (FriendInfo info : FamilyListActivity.arrayList) {

					if ((info.getUsername() + "@" + XmppTool.SERVER_NAME)
							.equals(chatName)) {
						info.setMessageCount(0);
					}
				}
				FamilyListActivity.fd
						.setArrayList(FamilyListActivity.arrayList);
				FamilyListActivity.fd.notifyDataSetChanged();
				// 获取消息并显示
				String json = msg.getData().getString("message");
				Log.d("zzzz", json);
				Gson gson = new Gson();
				Msg message = new Msg();
				message = gson.fromJson(json, new TypeToken<Msg>() {
				}.getType());

				ChatInformation chatif = new ChatInformation();
				chatif.setChatInformation(Msg.toJson(message));
				chatif.setuId(chatName);
				/*
				 * DBUtiles.saveChatInformation(chatif, ChatActivity.this,
				 * userName);
				 */
				list.add(message);
				adapter.setArraylist(list);
				adapter.notifyDataSetChanged();
				listview.setSelection(adapter.getCount() - 1);

				break;
			case 2:
				// 刷新适配器
				adapter.setArraylist(ChatActivity.list);
				adapter.notifyDataSetChanged();
				listview.setSelection(adapter.getCount() - 1);
				Log.d("zzzz", adapter.getCount() + "");
				/*
				 * MotionEvent ev = MotionEvent.obtain(0, 0,
				 * MotionEvent.ACTION_DOWN, 100, 100, 0, 0, 0, 0, 0, 0, 0);
				 * listview.dispatchTouchEvent(ev);
				 * 
				 * MotionEvent ev1 = MotionEvent.obtain(0, 0,
				 * MotionEvent.ACTION_UP, 100, 100, 0, 0, 0, 0, 0, 0, 0);
				 * listview.dispatchTouchEvent(ev1);
				 */
				break;
			case 5:
				Msg msg2 = new Msg("s", msg.getData().get("name").toString(),
						" ", " ", null);
				/*
				 * list.add(msg2); adapter.notifyDataSetChanged();
				 */
				MediaPlayer mp = new MediaPlayer();
				try {
					mp.setDataSource(msg.getData().getString("p"));
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					mp.prepare();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mp.start();
				break;
			case 9: // 接收文件
				Msg msg21 = (Msg) msg.getData().get("data");
				// 刷新适配器
				for (int i = 0; i < list.size(); i++) {
					if (list.get(i).getType().equals("record")
							|| list.get(i).getType().equals("photo")) {
						if (msg21.getFilePath().equals(
								list.get(i).getFilePath())) {

							list.get(i).setReceive(msg21.getReceive());
							Log.d("zzzz", list.get(i).getReceive() + "刷新适配器");
						}
					}
					Log.d("zzzz", list.get(i).getReceive());
				}
				adapter.setArraylist(list);
				adapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		};
	};

	class ChatClick implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.write:
				write.setVisibility(View.GONE);
				writeBack.setVisibility(View.VISIBLE);
				writeContent.setVisibility(View.VISIBLE);
				frameLayout.setVisibility(View.GONE);
				addAction.setVisibility(View.GONE);
				send1.setVisibility(View.VISIBLE);
				break;
			case R.id.writeBack:
				write.setVisibility(View.VISIBLE);
				writeBack.setVisibility(View.GONE);
				writeContent.setVisibility(View.GONE);
				frameLayout.setVisibility(View.VISIBLE);
				addAction.setVisibility(View.VISIBLE);
				send1.setVisibility(View.GONE);
				break;
			case R.id.headBackText:

				finish();
				break;
			case R.id.addAction:
				chatFlag = !chatFlag;
				if (chatFlag == true) {
					chat_picture.setVisibility(View.VISIBLE);
				} else {
					chat_picture.setVisibility(View.GONE);
				}
				break;
			case R.id.photograph:
				camera();
				chat_picture.setVisibility(View.GONE);
				chatFlag = !chatFlag;
				break;
			case R.id.gallery:
				gallery();
				chat_picture.setVisibility(View.GONE);
				chatFlag = !chatFlag;
				break;
			// 发消息
			case R.id.send1:
				String msg = writeContent.getText().toString();

				if (msg.length() > 0) {
					Msg message = new Msg(chatUserId, msg,
							TimeRender.getDate(), Msg.FROM_TYPE[0],
							Msg.TYPE[2], Msg.STATUS[3], null + "", null, bp);
					// 发送消息
					Msg message1 = new Msg(chatUserId, msg,
							TimeRender.getDate(), Msg.FROM_TYPE[1],
							Msg.TYPE[2], Msg.STATUS[3], null + "", null, bp);
					list.add(message1);
					// 刷新适配器
					adapter.notifyDataSetChanged();
					ChatInformation chatif = new ChatInformation();
					chatif.setChatInformation(Msg.toJson(message1));
					chatif.setuId(chatName);
					// /
					DBUtiles.saveChatInformation(chatif, ChatActivity.this,
							userName);
					listview.setSelection(adapter.getCount() - 1);

					try {
						newchat.sendMessage(Msg.toJson(message));
					} catch (XMPPException e) {
						e.printStackTrace();
					}catch (IllegalStateException e) {
						e.printStackTrace();
					}
				} else {
					Toast.makeText(ChatActivity.this, "请输入信息",
							Toast.LENGTH_SHORT).show();
				}
				writeContent.setText("");
				break;
			default:
				break;
			}
		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			onBackPressed();
		}
		return false;
	}

	/*
	 * 从相册获取
	 */
	public void gallery() {
		// 激活系统图库，选择一张图片
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
		startActivityForResult(intent, 1);
	}

	/*
	 * 从相机获取
	 */
	public void camera() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File tempFile = new File(Environment.getExternalStorageDirectory(),
				System.currentTimeMillis() + ".jpg");
		path = tempFile.getPath();
		sendFilePath = tempFile.getName();
		Log.d("zzzz", "自己拍照的路径" + path);
		// 从文件中创建uri
		uri = Uri.fromFile(tempFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		startActivityForResult(intent, 2);

	}

	/*
	 * 判断sdcard是否被挂载
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 获取图片
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 照相机
		if (resultCode == Activity.RESULT_OK && requestCode == 2) {
			if (hasSdcard()) {
				crop(uri);
			}
		}
		// 系统图库
		if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
			Uri uri = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(uri, filePathColumn,
					null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			File file = new File(picturePath);
			cursor.close();
			String sendfilepath = Environment.getExternalStorageDirectory()
					+ "/letianpai";
			File file1 = new File(sendfilepath);
			file.mkdirs();
			Log.d("zzzz", path);
			ImageTool.createThumbnail(file.getPath(), file1.getPath() + "/"
					+ file.getName());
			sendFile(file1.getPath() + "/" + file.getName());
			// sendFile(picturePath);
			Msg msg = new Msg(chatUserId, "图片", TimeRender.getDate(),
					Msg.FROM_TYPE[1], Msg.TYPE[1], Msg.STATUS[3], null + "",
					picturePath, bp);
			list.add(msg);
			Log.d("zzzz", "这路劲" + picturePath);
			adapter.notifyDataSetChanged();
			listview.setSelection(adapter.getCount() - 1);

			Msg msg1 = new Msg(chatUserId, "图片", TimeRender.getDate(),
					Msg.FROM_TYPE[0], Msg.TYPE[1], Msg.STATUS[3], null + "",
					file.getName(), bp);
			try {
				newchat.sendMessage(Msg.toJson(msg1));
			} catch (XMPPException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		// 调用照相机剪切后返回数据
		if (requestCode == 3) {
			if (data != null) {
				Bitmap bitmap = data.getParcelableExtra("data");
				String sendfilepath = Environment.getExternalStorageDirectory()
						+ "/letianpai";
				File file = new File(sendfilepath);
				file.mkdirs();
				Log.d("zzzz", path);
				ImageTool.createThumbnail(path, file.getPath() + "/"
						+ sendFilePath);
				sendFile(file.getPath() + "/" + sendFilePath);
				Msg msg = new Msg(chatUserId, "图片", TimeRender.getDate(),
						Msg.FROM_TYPE[1], Msg.TYPE[1], Msg.STATUS[3],
						null + "", path, bitmap);
				list.add(msg);
				adapter.notifyDataSetChanged();
				listview.setSelection(adapter.getCount() - 1);
				ChatUtils.saveChat(ChatActivity.this, msg, chatName, userName);
				/*
				 * ChatInformation chatif = new ChatInformation();
				 * chatif.setChatInformation(Msg.toJson(msg));
				 * chatif.setuId(chatName); // /
				 * DBUtiles.saveChatInformation(chatif, ChatActivity.this,
				 * userName);
				 */
				Msg msg1 = new Msg(chatUserId, "图片", TimeRender.getDate(),
						Msg.FROM_TYPE[0], Msg.TYPE[1], Msg.STATUS[3],
						null + "", sendFilePath, bitmap);
				try {
					newchat.sendMessage(Msg.toJson(msg1));
				} catch (XMPPException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	class MyFileStatusThread extends Thread {
		private FileTransfer transfer;
		private Msg msg;

		public MyFileStatusThread(FileTransfer tf) {
			transfer = tf;
		}

		public MyFileStatusThread(FileTransfer tf, Msg msg) {
			transfer = tf;
			this.msg = msg;
		}

		public void run() {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Log.d("ww", transfer.getStatus() + "");
				android.os.Message message = new android.os.Message();// handle
				message.what = 3;
				while (!transfer.isDone()) {
					System.out.println(transfer.getStatus());
					System.out.println(transfer.getProgress());

				}

				if (transfer.getStatus().equals(Status.error)) {
					msg.setReceive(Msg.STATUS[2]);
					break;
				} else if (transfer.getStatus().equals(Status.refused)) {
					msg.setReceive(Msg.STATUS[1]);
					break;
				} else if (transfer.getStatus().equals(Status.complete)) {
					msg.setReceive(Msg.STATUS[0]);// 成功
					Log.d("zzzz", "接收成功");
					break;
				}

				handler.sendMessage(message);
			}

		}
	}

	private void sendFile(String filepath) {
		final FileTransferManager fileTransferManager = new FileTransferManager(
				XmppTool.con);
		FileTransferNegotiator.setServiceEnabled(XmppTool.con, true);
		final OutgoingFileTransfer fileTransfer = fileTransferManager
				.createOutgoingFileTransfer(userChat + "/Smack");
		final File file = new File(filepath);
		Log.d("zzzz", filepath + "发送图片文件的地址或者音频文件的地址");
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					fileTransfer.sendFile(file, "Sending");
					Status status = fileTransfer.getStatus();
					while (status == FileTransfer.Status.complete) {

					}
				} catch (XMPPException e1) {
					e1.printStackTrace();
				}
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Msg msgInfo = queryMsgForListMsg(file.getName());

				try {
					while (true) {

						Thread.sleep(100);
						Status status = fileTransfer.getStatus();
						Log.d("zzzz", status.toString() + "传送文件的状态");

						if (status.equals(Status.error)) {
							msgInfo.setReceive(Msg.STATUS[2]);
							break;
						} else if (status.equals(Status.refused)) {
							msgInfo.setReceive(Msg.STATUS[1]);
							break;
						} else if (status.equals(Status.complete)) {
							Log.d("zzzz", "接收成功");
							msgInfo.setReceive(Msg.STATUS[0]);// 成功
							break;

						} else if (status.equals(Status.in_progress)) {
							msgInfo.setReceive(Msg.STATUS[0]);// 成功
							break;
						}

						if ((status == FileTransfer.Status.error)
								|| (status == FileTransfer.Status.complete)
								|| (status == FileTransfer.Status.cancelled)
								|| (status == FileTransfer.Status.refused)) {
							handler.sendEmptyMessage(4);
							break;
						} else if (status == FileTransfer.Status.negotiating_transfer) {
							// ..
						} else if (status == FileTransfer.Status.negotiated) {
							// ..
						} else if (status == FileTransfer.Status.initial) {
							// ..
						} else if (status == FileTransfer.Status.negotiating_stream) {
							// ..
						} else if (status == FileTransfer.Status.in_progress) {
							// 进度条显示
							handler.sendEmptyMessage(2);

							long p = fileTransfer.getBytesSent() * 100L
									/ fileTransfer.getFileSize();

							android.os.Message message = handler
									.obtainMessage();
							message.arg1 = Math.round((float) p);
							message.what = 3;
							message.sendToTarget();
							Toast.makeText(ChatActivity.this, "发送成功!",
									Toast.LENGTH_SHORT).show();

						}
					}
					android.os.Message message = new android.os.Message();// handle
					Bundle bundle = new Bundle();
					bundle.putSerializable("data", msgInfo);
					message.setData(bundle);
					message.what = 9;
					handler.sendMessage(message);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	/**
	 * 接收文件
	 * 
	 * @author Administrator
	 * 
	 * 
	 */
	public void receivedFile() {
		final FileTransferManager manager = new FileTransferManager(
				XmppTool.con);
		ServiceDiscoveryManager sdm = ServiceDiscoveryManager
				.getInstanceFor(XmppTool.con);
		if (sdm == null)
			sdm = new ServiceDiscoveryManager(XmppTool.con);
		sdm.addFeature("http://jabber.org/protocol/disco#info");
		sdm.addFeature("jabber:iq:privacy");
		// Create the file transfer manager

		FileTransferNegotiator.setServiceEnabled(XmppTool.con, true);
		manager.addFileTransferListener(new FileTransferListener() {

			public void fileTransferRequest(FileTransferRequest request) {
				if (shouldAccept(request)) {
					Log.d("zzzz", request.getFileSize() / 1024 + "文件大小");
					final IncomingFileTransfer transfer = request.accept();
					final File file = new File(RECORD_ROOT_PATH
							+ request.getFileName());
					try {
						transfer.recieveFile(file);
						Log.d("ww", transfer.isDone() + "");

					} catch (XMPPException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					/*
					 * Msg msgInfo = queryMsgForListMsg(file.getName());
					 * msgInfo.setFilePath(file.getPath());// 更新 filepath new
					 * MyFileStatusThread(transfer, msgInfo).start();
					 */

					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								Thread.sleep(500);
							} catch (InterruptedException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							Msg msgInfo = queryMsgForListMsg(file.getName());
							Log.d("zzzz", file.getName() + "接收的文件名称");
							Log.d("zzzz", msgInfo.getFilePath() + "检索的msg的文件名称");
							while (true) {
								try {
									Thread.sleep(500);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								Log.d("ww", transfer.isDone() + "");
								Log.d("ww", transfer.getStatus().toString()
										+ "传送状态");
								if (transfer.getStatus().equals(Status.error)) {
									msgInfo.setReceive(Msg.STATUS[2]);
									break;
								} else if (transfer.getStatus().equals(
										Status.refused)) {
									msgInfo.setReceive(Msg.STATUS[1]);
									break;
								} else if (transfer.getStatus().equals(
										Status.complete)) {
									Log.d("zzzz", "接收成功");
									msgInfo.setReceive(Msg.STATUS[0]);// 成功
									break;

								}

							}
							android.os.Message message = new android.os.Message();// handle
							Bundle bundle = new Bundle();
							bundle.putSerializable("data", msgInfo);
							message.setData(bundle);
							message.what = 9;
							handler.sendMessage(message);

						}
					}).start();
				} else {

				}
			}
		});
	}

	/**
	 * 从list 中取出 分拣名称相同的 Msg没有返回最后一个
	 */
	private Msg queryMsgForListMsg(String filePath) {

		Msg msg = new Msg();
		msg.setFilePath("");
		Log.d("zzzz", filePath + "这里是去检索的文件名称");
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getType().equals("record")
					|| list.get(i).getType().equals("photo")) {
				msg = list.get(i);
				Log.d("zzzz", list.get(i).getFilePath() + "这里是for循环的文件名称");
				if (null != filePath && filePath.equals(msg.getFilePath())) {// 对方传过来的只是文件的名称
					return msg;
				}
			}
		}
		return msg;
	}

	/**
	 * 是否接收
	 * 
	 * @param request
	 * @return
	 */
	private boolean shouldAccept(FileTransferRequest request) {
		final boolean isAccept[] = new boolean[1];

		return true;
	}

	// 设置聊天记录点击事件
	class ChatInformationClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view,
				final int position, long id) {
			if (list.get(position).getType().equals("record")) {
				list.get(position).setPlaystatu(1);
				adapter.setArraylist(list);
				adapter.notifyDataSetChanged();
				new Thread(new Runnable() {

					@Override
					public void run() {
						MediaPlayer mp = new MediaPlayer();
						Log.d("zzzz", list.get(position).getFilePath());
						try {
							if (list.get(position).getFrom().equals("OUT")) {
								mp.setDataSource(list.get(position)
										.getFilePath());
							} else {
								mp.setDataSource("/storage/sdcard0/chat/"
										+ "record/"
										+ list.get(position).getFilePath());
							}
						} catch (IllegalArgumentException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SecurityException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							mp.prepare();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mp.start();
						String a = list.get(position).getTime();
						long b = Long.parseLong(a) * 1000;
						try {
							Thread.sleep(b);
							mp.release();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();

			} else if (list.get(position).getType().equals("photo")) {
				Intent intent = new Intent(ChatActivity.this,
						ShowImageActivity.class);
				intent.putExtra("filepath", list.get(position).getFilePath());
				intent.putExtra("from", list.get(position).getFrom());
				startActivity(intent);
			}
		}

	}

	/*
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, 3);
	}

	public void getUserBitmap() {
		// Access to chat the head of both sides 
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					mb = ChatUtils.getUserImage(userName);
					ub = ChatUtils.getUserImage(Utils
							.getJidToUsername(chatName));
					adapter.setBitmap(mb, ub);
					adapter.notifyDataSetChanged();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}
}
